package sing.core.callback.livedata

import androidx.lifecycle.MutableLiveData

class LiveDataBus private constructor() {

    // 存放订阅者
    private val bus: MutableMap<String, MutableLiveData<Any>>
    init {
        bus = HashMap()
    }

    // 注册订阅者，（存入map）
    @Synchronized
//    fun <T> with(key: String, type: Class<T>): MutableLiveData<T> {
    fun <T> with(key: String): MutableLiveData<T> {
        if (!bus.containsKey(key)) {
            bus[key] = MutableLiveData<Any>()
        }
        return bus[key] as MutableLiveData<T>
    }

    @Synchronized
    fun withInt(key: String): MutableLiveData<Int> {
        if (!bus.containsKey(key)) {
            bus[key] = MutableLiveData<Any>()
        }
        return bus[key] as MutableLiveData<Int>
    }

    @Synchronized
    fun withBool(key: String): MutableLiveData<Boolean> {
        if (!bus.containsKey(key)) {
            bus[key] = MutableLiveData<Any>()
        }
        return bus[key] as MutableLiveData<Boolean>
    }

    @Synchronized
    fun withString(key: String): MutableLiveData<String> {
        if (!bus.containsKey(key)) {
            bus[key] = MutableLiveData<Any>()
        }
        return bus[key] as MutableLiveData<String>
    }
    @Synchronized
    fun remove(key: String) {
        if (bus.containsKey(key)) {
            bus.remove(key)
        }
    }

    companion object {
        val instance = LiveDataBus()
    }
}